package cn.dyhack.bibiscan.dao.impl;

import static cn.dyhack.bibiscan.po.tables.User.USER;

import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.dyhack.bibiscan.dao.UserMapper;
import cn.dyhack.bibiscan.po.tables.pojos.User;
import cn.dyhack.bibiscan.po.tables.records.UserRecord;

@Repository("userMapper")
public class UserMapperImpl implements UserMapper {

    @Autowired
    private DSLContext dsl;

    /**
     * 
     * 添加一个用户
     *
     * @param user
     *            用户对象
     * @return 插入成功返回用户的对象,失败返回null
     * @author zhangke
     * @since 0.0.1
     */
    @Transactional
    public User addUser(User user) {
        UserRecord userRecord = dsl.newRecord(USER);
        userRecord.from(user);
        if (userRecord.store() == 1) {
            return user;
        }
        return null;
    }

    /**
     * 
     * 删除一个用户
     *
     * @param id
     *            用户的id
     * @author zhangke
     * @since 0.0.1
     */
    @SuppressWarnings("deprecation")
    @Transactional
    public void delUser(Long id) {
        dsl.deleteFrom(USER)
                .where(USER.ID.equals(id));

    }

    /**
     * 
     * 通过用户名称查找用户
     *
     * @param userName
     *            用户名称
     * @return 用户对象
     * @author zhangke
     * @since 0.0.1
     */
    public User selectUserByName(String userName) {
        UserRecord userRecord = dsl.selectFrom(USER)
                .where(USER.USERNAME.eq(userName))
                .fetchOne();
        if (userRecord != null) {
            return userRecord.into(User.class);
        }
        return null;
    }

    /**
     * 
     * 更新用户
     *
     * @param userName
     * @return 更新成功的用户对象
     * @author zhangke
     * @since 0.0.1
     */
    @Transactional
    public User updateUser(User user) {
        UserRecord userRecord = dsl.newRecord(USER);
        userRecord.from(user);
        userRecord.changed(USER.ID, false);
        if (userRecord.store() == 1) {
            return selectUserById(userRecord.getId());
        }
        return null;
    }

    /**
     * 
     * 通过id查找用户
     *
     * @param id
     * @return 用户对象
     * @author zhangke
     * @since 0.0.1
     */
    public User selectUserById(Long id) {
        UserRecord userRecord = dsl.selectFrom(USER)
                .where(USER.ID.eq(id))
                .fetchOne();
        if (userRecord != null) {
            return userRecord.into(User.class);
        }
        return null;
    }

}
